<template>
  <div class="auth-container">
    <!-- 自定义标题栏 (仅在Electron环境下显示) -->
    <TitleBar v-if="isElectron" />

    <!-- 背景装饰 -->
    <div class="auth-background">
      <div class="bg-pattern"></div>
      <div class="bg-gradient"></div>
    </div>

    <div class="auth-content">
      <!-- 品牌展示区 -->
      <div class="brand-section">
        <div class="brand-content">
          <div class="brand-logo">
            <el-icon class="logo-icon"><Folder /></el-icon>
            <h1 class="logo-text">RickPan</h1>
          </div>

          <div class="brand-description">
            <h2>开启您的云端之旅</h2>
            <p>加入数千家企业的选择，体验专业级文件管理服务</p>

            <div class="feature-highlights">
              <div class="feature-item">
                <el-icon><UserFilled /></el-icon>
                <span>个人空间</span>
              </div>
              <div class="feature-item">
                <el-icon><Share /></el-icon>
                <span>团队协作</span>
              </div>
              <div class="feature-item">
                <el-icon><Lock /></el-icon>
                <span>数据安全</span>
              </div>
            </div>

            <div class="stats">
              <div class="stat-item">
                <span class="stat-number">10TB</span>
                <span class="stat-label">免费存储</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">99.9%</span>
                <span class="stat-label">可用性</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">24/7</span>
                <span class="stat-label">技术支持</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 注册表单区 -->
      <div class="form-section">
        <div class="form-container theme-card">
          <!-- 主题切换按钮 -->
          <div class="theme-toggle">
            <el-tooltip :content="themeStore.isDark ? '切换到日间模式' : '切换到夜间模式'" placement="left">
              <el-button
                text
                circle
                @click="themeStore.toggleTheme()"
                class="theme-toggle-btn"
              >
                <el-icon>
                  <Sunny v-if="themeStore.isDark" />
                  <Moon v-else />
                </el-icon>
              </el-button>
            </el-tooltip>
          </div>

          <div class="form-header">
            <h2>创建您的账户</h2>
            <p>几分钟即可完成注册，立即开始使用</p>
          </div>

          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            size="large"
            class="auth-form"
            @submit.prevent="handleSubmit"
          >
            <div class="form-row">
              <el-form-item prop="username" class="form-col">
                <div class="input-wrapper">
                  <label class="input-label">用户名</label>
                  <el-input
                    v-model="form.username"
                    placeholder="请输入用户名"
                    :prefix-icon="User"
                    clearable
                    class="theme-input"
                  />
                  <div class="input-help">
                    <el-text size="small" type="info">
                      3-20字符，支持字母、数字、下划线
                    </el-text>
                  </div>
                </div>
              </el-form-item>

              <el-form-item prop="email" class="form-col">
                <div class="input-wrapper">
                  <label class="input-label">邮箱地址</label>
                  <el-input
                    v-model="form.email"
                    placeholder="请输入邮箱地址"
                    :prefix-icon="Message"
                    clearable
                    class="theme-input"
                  />
                  <div class="input-help">
                    <el-text size="small" type="info">
                      用于账户验证和密码找回
                    </el-text>
                  </div>
                </div>
              </el-form-item>
            </div>

            <el-form-item prop="realName">
              <div class="input-wrapper">
                <label class="input-label">真实姓名 <span class="optional">(可选)</span></label>
                <el-input
                  v-model="form.realName"
                  placeholder="请输入您的真实姓名"
                  :prefix-icon="UserFilled"
                  clearable
                  class="theme-input"
                />
                <div class="input-help">
                  <el-text size="small" type="info">
                    最多50个字符，用于个人资料显示
                  </el-text>
                </div>
              </div>
            </el-form-item>

            <div class="form-row">
              <el-form-item prop="password" class="form-col">
                <div class="input-wrapper">
                  <label class="input-label">密码</label>
                  <el-input
                    v-model="form.password"
                    type="password"
                    placeholder="请输入密码"
                    :prefix-icon="Lock"
                    show-password
                    clearable
                    class="theme-input"
                  />
                  <div class="input-help">
                    <el-text size="small" type="info">
                      6-20字符，必须包含字母和数字
                    </el-text>
                  </div>
                </div>
              </el-form-item>

              <el-form-item prop="confirmPassword" class="form-col">
                <div class="input-wrapper">
                  <label class="input-label">确认密码</label>
                  <el-input
                    v-model="form.confirmPassword"
                    type="password"
                    placeholder="请再次输入密码"
                    :prefix-icon="Lock"
                    show-password
                    clearable
                    class="theme-input"
                    @keyup.enter="handleSubmit"
                  />
                  <div class="input-help">
                    <el-text size="small" type="info">
                      请再次输入上面的密码进行确认
                    </el-text>
                  </div>
                </div>
              </el-form-item>
            </div>

            <el-form-item>
              <div class="terms-wrapper">
                <el-checkbox v-model="agreeTerms" class="terms-checkbox">
                  我已阅读并同意
                  <el-link type="primary" :underline="false" class="terms-link">服务条款</el-link>
                  和
                  <el-link type="primary" :underline="false" class="terms-link">隐私政策</el-link>
                </el-checkbox>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="authStore.loading"
                :disabled="!agreeTerms"
                @click="handleSubmit"
                class="submit-btn theme-button-primary"
              >
                <span v-if="!authStore.loading">
                  <el-icon><Right /></el-icon>
                  创建账户
                </span>
                <span v-else>
                  注册中...
                </span>
              </el-button>
            </el-form-item>
          </el-form>

          <div class="form-footer">
            <div class="divider">
              <span>或</span>
            </div>

            <p class="login-prompt">
              已有账户？
              <router-link to="/auth/login" class="login-link theme-link">
                立即登录
              </router-link>
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  User,
  Lock,
  Message,
  UserFilled,
  Folder,
  Share,
  Right,
  Sunny,
  Moon
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { useThemeStore } from '@/stores/theme'
import TitleBar from '@/components/electron/TitleBar.vue'
import type { RegisterRequest } from '@/types'
import { getElementPlusRules, handleBackendValidationErrors, showFieldErrors, validators } from '@/utils/validation'

const router = useRouter()
const authStore = useAuthStore()
const themeStore = useThemeStore()

// 检查是否在Electron环境
const isElectron = computed(() => {
  return !!(window as any).electronAPI
})

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const form = reactive<RegisterRequest & { confirmPassword: string }>({
  username: '',
  email: '',
  realName: '',
  password: '',
  confirmPassword: ''
})

// 同意条款
const agreeTerms = ref(false)

// 表单验证规则 - 使用统一的验证规则
const validationRules = getElementPlusRules()
const rules: FormRules = {
  ...validationRules.register,
  // 确认密码需要特殊处理
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: Function) => {
        const error = validators.confirmPassword(value, form.password)
        if (error) {
          callback(new Error(error))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  if (!agreeTerms.value) {
    ElMessage.warning('请先同意服务条款和隐私政策')
    return
  }

  try {
    // 前端验证表单
    await formRef.value.validate()

    // 准备注册数据
    const registerData: RegisterRequest = {
      username: form.username.trim(),
      email: form.email.trim(),
      password: form.password,
      realName: form.realName?.trim() || undefined
    }

    // 执行注册
    const success = await authStore.register(registerData)

    if (success) {
      // 注册成功，跳转到登录页
      router.push('/auth/login')
    }
  } catch (error: any) {
    console.error('注册失败:', error)

    // 处理后端验证错误
    if (error.response?.status === 400 && error.response?.data?.data) {
      // 后端返回的字段验证错误
      const backendErrors = error.response.data.data
      const validationErrors = handleBackendValidationErrors(backendErrors)

      // 在表单中显示字段级别的错误
      showFieldErrors(formRef.value, validationErrors)

      // 显示总体错误提示
      ElMessage.error('请检查输入信息')
    } else if (error.response?.data?.message) {
      // 显示后端返回的具体错误信息
      ElMessage.error(error.response.data.message)
    } else {
      // 显示通用错误信息
      ElMessage.error('注册失败，请重试')
    }
  }
}
</script>

<style lang="scss" scoped>
// ==================== 主容器 ====================
.auth-container {
  position: relative;
  min-height: 100vh;
  display: flex;
  flex-direction: column; // 改为垂直布局，标题栏在顶部，内容在下方
  overflow-x: hidden;
  overflow-y: auto;
}

// ==================== 背景装饰 ====================
.auth-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;

  .bg-pattern {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image:
      radial-gradient(circle at 25% 25%, var(--theme-primary-bg) 0%, transparent 50%),
      radial-gradient(circle at 75% 75%, var(--theme-primary-bg) 0%, transparent 50%);
    opacity: 0.3;
  }

  .bg-gradient {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
      135deg,
      var(--bg-color-primary) 0%,
      var(--bg-color-secondary) 100%
    );
  }
}

// ==================== 内容区域 ====================
.auth-content {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 80px;
  align-items: center;
  flex: 1; // 占据剩余空间
  min-height: 0; // 允许flex收缩

  @media (max-width: 1024px) {
    grid-template-columns: 1fr;
    gap: 40px;
    max-width: 520px;
  }

  @media (max-width: 768px) {
    padding: 16px;
    gap: 32px;
  }
}

// ==================== 品牌展示区 ====================
.brand-section {
  display: flex;
  flex-direction: column;
  justify-content: center;

  @media (max-width: 1024px) {
    text-align: center;
    order: 2;
  }
}

.brand-content {
  .brand-logo {
    display: flex;
    align-items: center;
    margin-bottom: 32px;

    @media (max-width: 1024px) {
      justify-content: center;
    }

    .logo-icon {
      font-size: 48px;
      color: var(--theme-primary);
      margin-right: 16px;
    }

    .logo-text {
      font-size: 36px;
      font-weight: 700;
      color: var(--text-color-primary);
      margin: 0;
      background: linear-gradient(135deg, var(--theme-primary), var(--theme-primary-light));
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
  }

  .brand-description {
    h2 {
      font-size: 28px;
      font-weight: 600;
      color: var(--text-color-primary);
      margin: 0 0 16px 0;
      line-height: 1.3;

      @media (max-width: 768px) {
        font-size: 24px;
      }
    }

    p {
      font-size: 16px;
      color: var(--text-color-secondary);
      line-height: 1.6;
      margin: 0 0 32px 0;
    }
  }

  .feature-highlights {
    display: flex;
    gap: 16px;
    margin-bottom: 32px;

    @media (max-width: 1024px) {
      justify-content: center;
    }

    @media (max-width: 768px) {
      flex-direction: column;
      gap: 12px;
    }

    .feature-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 10px 14px;
      background-color: var(--bg-color-tertiary);
      border-radius: 8px;
      border: 1px solid var(--border-color-light);
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: var(--shadow-base);
      }

      .el-icon {
        font-size: 16px;
        color: var(--theme-primary);
      }

      span {
        font-size: 13px;
        font-weight: 500;
        color: var(--text-color-secondary);
      }
    }
  }

  .stats {
    display: flex;
    gap: 24px;

    @media (max-width: 1024px) {
      justify-content: center;
    }

    @media (max-width: 768px) {
      gap: 16px;
    }

    .stat-item {
      text-align: center;

      .stat-number {
        display: block;
        font-size: 24px;
        font-weight: 700;
        color: var(--theme-primary);
        line-height: 1;
        margin-bottom: 4px;
      }

      .stat-label {
        font-size: 12px;
        color: var(--text-color-tertiary);
        font-weight: 500;
      }
    }
  }
}

// ==================== 表单区域 ====================
.form-section {
  display: flex;
  justify-content: center;

  @media (max-width: 1024px) {
    order: 1;
  }
}

.form-container {
  position: relative;
  width: 100%;
  max-width: 460px;
  max-height: 85vh;
  padding: 20px;
  border-radius: 16px;
  backdrop-filter: blur(10px);
  overflow-y: auto;

  @media (max-width: 768px) {
    padding: 16px 12px;
    border-radius: 12px;
    max-width: 100%;
    max-height: 80vh;
  }

  @media (max-width: 480px) {
    padding: 12px 10px;
    max-height: 75vh;
  }
}

// ==================== 主题切换按钮 ====================
.theme-toggle {
  position: absolute;
  top: 16px;
  right: 16px;

  .theme-toggle-btn {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: var(--bg-color-secondary);
    border: 1px solid var(--border-color-light);
    transition: all 0.3s ease;

    &:hover {
      background-color: var(--theme-primary-bg);
      border-color: var(--theme-primary);
      transform: scale(1.05);
    }

    .el-icon {
      font-size: 18px;
      color: var(--theme-primary);
    }
  }
}

// ==================== 表单头部 ====================
.form-header {
  text-align: center;
  margin-bottom: 16px;

  h2 {
    font-size: 20px;
    font-weight: 600;
    color: var(--text-color-primary);
    margin: 0 0 2px 0;
  }

  p {
    font-size: 12px;
    color: var(--text-color-secondary);
    margin: 0;
    line-height: 1.2;
  }
}

// ==================== 表单样式 ====================
.auth-form {
  .form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
    margin-bottom: 16px;

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
      gap: 0;
      margin-bottom: 0;
    }

    .form-col {
      margin-bottom: 0;

      @media (max-width: 768px) {
        margin-bottom: 16px;
      }

      .input-wrapper {
        margin-bottom: 0;
      }
    }
  }

  .input-wrapper {
    margin-bottom: 20px; // 增加底部间距为错误信息留空间
    position: relative;

    .input-label {
      display: block;
      font-size: 12px;
      font-weight: 500;
      color: var(--text-color-primary);
      margin-bottom: 3px;

      .optional {
        color: var(--text-color-tertiary);
        font-weight: 400;
        font-size: 10px;
      }
    }

    .input-help {
      margin-top: 3px;

      .el-text {
        color: var(--el-text-color-placeholder);
        font-size: 10px;
        line-height: 1.3;
      }
    }
  }

  .terms-wrapper {
    margin-bottom: 12px;

    .terms-checkbox {
      :deep(.el-checkbox__label) {
        color: var(--text-color-secondary);
        font-size: 11px;
        line-height: 1.2;
      }

      .terms-link {
        font-size: 12px;
        font-weight: 500;
        margin: 0 2px;
      }
    }
  }

  .submit-btn {
    width: 100%;
    height: 42px;
    font-size: 14px;
    font-weight: 600;
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover:not(:disabled) {
      transform: translateY(-1px);
      box-shadow: var(--theme-primary-shadow);
    }

    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }

    .el-icon {
      margin-right: 6px;
    }
  }
}

// ==================== 表单底部 ====================
.form-footer {
  margin-top: 12px;
  text-align: center;

  .divider {
    position: relative;
    margin: 12px 0;

    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 0;
      right: 0;
      height: 1px;
      background-color: var(--border-color-light);
    }

    span {
      position: relative;
      background-color: var(--bg-color-tertiary);
      padding: 0 12px;
      font-size: 12px;
      color: var(--text-color-tertiary);
    }
  }

  .login-prompt {
    font-size: 12px;
    color: var(--text-color-secondary);
    margin: 0;

    .login-link {
      font-weight: 600;
      text-decoration: none;
      margin-left: 4px;

      &:hover {
        text-decoration: underline;
      }
    }
  }
}

// ==================== 深度样式覆盖 ====================
:deep(.el-form-item) {
  margin-bottom: 0;

  .el-form-item__error {
    color: var(--color-danger);
    font-size: 12px;
    margin-top: 4px;
  }
}

:deep(.el-input) {
  .el-input__wrapper {
    background-color: var(--bg-color-tertiary);
    border: 1px solid var(--border-color-light);
    border-radius: 6px;
    padding: 8px 12px;
    transition: all 0.3s ease;
    box-shadow: none;
    min-height: 36px;

    &:hover {
      border-color: var(--theme-primary);
    }

    &.is-focus {
      border-color: var(--theme-primary);
      box-shadow: 0 0 0 2px var(--theme-primary-bg);
    }

    &.is-error {
      border-color: var(--color-danger);

      &.is-focus {
        box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.1);
      }
    }
  }

  .el-input__inner {
    height: auto;
    line-height: 1.4;
    color: var(--text-color-primary);
    font-size: 13px;

    &::placeholder {
      color: var(--text-color-tertiary);
    }
  }

  .el-input__prefix {
    color: var(--text-color-tertiary);
  }

  .el-input__suffix {
    color: var(--text-color-tertiary);
  }
}

:deep(.el-checkbox) {
  .el-checkbox__input {
    .el-checkbox__inner {
      background-color: var(--bg-color-tertiary);
      border-color: var(--border-color-base);

      &:hover {
        border-color: var(--theme-primary);
      }
    }

    &.is-checked .el-checkbox__inner {
      background-color: var(--theme-primary);
      border-color: var(--theme-primary);
    }
  }

  .el-checkbox__label {
    color: var(--text-color-secondary);
    font-size: 14px;
    line-height: 1.5;
  }
}

:deep(.el-button) {
  &.is-loading {
    .el-icon {
      margin-right: 0;
    }
  }
}

// ==================== 响应式优化 ====================
@media (max-width: 768px) {
  .auth-content {
    grid-template-columns: 1fr;
    gap: 32px;
    max-width: 100%;
  }

  .form-container {
    max-width: 100%;
  }

  .auth-form {
    .form-row {
      grid-template-columns: 1fr;
      gap: 0;
      margin-bottom: 0;

      .form-col {
        margin-bottom: 24px;

        &:last-child {
          margin-bottom: 24px;
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .auth-content {
    padding: 12px;
  }

  .form-container {
    padding: 24px 16px;
    border-radius: 8px;
  }

  .brand-content {
    .brand-logo {
      .logo-icon {
        font-size: 40px;
      }

      .logo-text {
        font-size: 28px;
      }
    }

    .brand-description h2 {
      font-size: 20px;
    }

    .feature-highlights {
      .feature-item {
        padding: 8px 12px;

        span {
          font-size: 12px;
        }
      }
    }

    .stats {
      .stat-item {
        .stat-number {
          font-size: 20px;
        }
      }
    }
  }

  .form-header h2 {
    font-size: 24px;
  }

  .theme-toggle {
    top: 12px;
    right: 12px;

    .theme-toggle-btn {
      width: 36px;
      height: 36px;
    }
  }
}
</style>
